using System.Collections;
using System.Diagnostics;
using System.Text;
using UnityEngine.Networking;

namespace Framework
{
    public class UnityHttpRequest : HttpRequestAgent
    {
        private static StringBuilder stringBuilder = new StringBuilder();
        private static UTF8Encoding encoding = new UTF8Encoding();
        private byte[] PostData;
        public override void Clear()
        {
            base.Clear();
            PostData = null;
        }
        protected override void onSend()
        {
            if (coroutineManager != null)
            {
                coroutineManager.Start(send(), this.GetType().ToString());
            }
            else
            {
                FrameworkLog.LogError("not set coroutineManager");
            }
            //FrameworkCore.Instance.Coroutine.StartCoroutine(send(), this.GetType().ToString());
        }
        IEnumerator send()
        {
            int count = Task.Retry;
            if (count < 1) count = 1;
            if (Task.PostType == HttpPostType.url)
            {
                var len = Task.FormData.Count;
                for (int i = 0; i < len; i++)
                {
                    var item = Task.FormData[i];
                    string key = item.sectionName;
                    if (string.IsNullOrEmpty(key) && item.sectionData == null)
                    {
                        continue;
                    }
                    if (i > 0)
                    {
                        stringBuilder.Append("&");
                    }
                    if (!string.IsNullOrEmpty(key))
                    {
                        stringBuilder.Append(key);
                        stringBuilder.Append("=");
                    }
                    if (item.sectionData != null)
                    {
                        // stringBuilder.Append(System.Uri.EscapeDataString(encoding.GetString(item.sectionData)));
                        stringBuilder.Append(encoding.GetString(item.sectionData));
                    }
                }
                var str = stringBuilder.ToString();
                stringBuilder.Clear();
                PostData = encoding.GetBytes(str);
            }
            while (count-- > 0)
            {
                UnityWebRequest www;
                if (Task.PostType == HttpPostType.form)
                {
                    www = UnityWebRequest.Post(Task.URL, Task.FormData);
                }
                else if (Task.PostType == HttpPostType.url)
                {
                    www = new UnityWebRequest(Task.URL, UnityWebRequest.kHttpVerbPOST);
                    www.uploadHandler = (UploadHandler)new UploadHandlerRaw(PostData);
                    www.uploadHandler.contentType = "application/x-www-form-urlencoded";
                    www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                }
                else if (Task.PostType == HttpPostType.json)
                {
                    var item = Task.FormData[0];
                    www = new UnityWebRequest(Task.URL, UnityWebRequest.kHttpVerbPOST);
                    www.uploadHandler = (UploadHandler)new UploadHandlerRaw(item.sectionData);
                    www.uploadHandler.contentType = "application/json";
                    www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                }
                else if (Task.PostType == HttpPostType.bytes)
                {
                    var item = Task.FormData[0];
                    www = new UnityWebRequest(Task.URL, UnityWebRequest.kHttpVerbPOST);
                    www.uploadHandler = (UploadHandler)new UploadHandlerRaw(item.sectionData);
                    www.uploadHandler.contentType = "application/octet-stream";
                    www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                }
                else
                {
                    www = UnityWebRequest.Get(Task.URL);
                }
                if (Task.Headers != null)
                {
                    foreach (var item in Task.Headers)
                    {
                        www.SetRequestHeader(item.Key, item.Value);
                    }
                }
                yield return www.SendWebRequest();
                if (!Utils.Unity.IsUnityWebRequestError(www))
                {
                    count = -1;
                    Complete(false, www.downloadHandler.data);
                    www.Dispose();
                    yield break;
                }
                www.Dispose();
            }
            Complete(true);
        }
    }
}
